<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\validate\LoginValidate;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\View;
use think\facade\Event;

class Login extends Diluma
{
    /**
     * 登录首页
     * @return void
     */
    public function index(){
        return redirect('/admin/login/login');
    }

    /**
     * 登录
     * @return string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login()
    {
        if(!Session::has('{ADMIN_LOGIN_INFO}')) {
            if($this->request->isPost()) {
                $post = $this->request->post();
                // 验证参数
                validate(LoginValidate::class)->scene('login')->checkData($post);
                // 验证码
                $captcha = trim($post['captcha']);
                if (!captcha_check($captcha)) {
                    return json(['code'=>1, 'msg'=>'验证码不正确']);
                }
                // 验证用户名
                $user = Db::table('dlm_admin_user')->where('username', trim($post['username']))->where(['delete_time'=>0])->find();
                if(empty($user)) {
                    return message("用户名不存在", false);
                }
                if($user['status'] <> 1) {
                    return message("用户名已被禁用，请联系管理员解决", false);
                }
                // 验证密码
                $post['password'] = md5($post['password']);
                if($user['password'] != $post['password']) {
                    return message("密码错误", false);
                }
                // 是否记住账号
                if(!empty($post['remember_me']) && $post['remember_me'] == 1) {
                    Cookie::forever('remember_me', $post['username']);
                } else {
                    if(Cookie::has('remember_me')) {
                        Cookie::delete('remember_me');
                    }
                }
                Session::set('{ADMIN_LOGIN_INFO}', [
                    'admin_id' => $user['id'],
                    'role_id' => $user['role_id'],
                    'username' => $user['username'],
                    'nickname' => $user['nickname'],
                    'gender' => $user['gender'],
                    'avatar' => $user['avatar'],
                    'login_time' => $user['login_time'], // 上一次登录时间
                    'login_ip' => $this->request->ip()
                ]);
                // 记录登录时间和ip
                Db::table('dlm_admin_user')->where('id', $user['id'])->update(['login_ip'=>$this->request->ip(), 'login_time'=>time()]);
                // 登录事件
                Event::trigger("AdminLogin", new \app\admin\event\Login($user['id']));
                return message('登录成功,正在跳转..',true, '/admin/index/index');
            } else {
                if(Cookie::has('remember_me')) {
                    View::assign('remember_me', Cookie::get('remember_me'));
                }
                View::assign('_site_url', SITE_URL);
                return View::fetch('login');
            }
        } else {
            return redirect('/admin/index/index');
        }
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout()
    {
        session(null);
        if(Session::has('{ADMIN_LOGIN_INFO}')) {
            return message('退出失败',false);
        } else {
            return message('正在退出...', true, '/admin/login/login');
        }
    }
}